/** @jsxImportSource @emotion/react */
import { jsx, css } from "@emotion/react";
import * as React from "react";
import {
    List,
    ListItem,
    Avatar,
    Text, Stack, StackTitle, StackItem,
    useTheme,
    IconChevronRight,
    useMMenuBarOcup,
    Button,
    VerticalMenu,
    DdMenuItem,
    useToast,
    MenuItem,
    IconLayers,
    DialogContent,
    DialogHeading,
    DialogDescription,
    InputLine,
    CommitInput,
    Input, ButtonRefComp, DialogClose, Dialog
} from "customize-easy-ui-component";
import {usePaginationFragment, useRefetchableFragment} from "react-relay/hooks";
import {MeIspList$key} from "./__generated__/MeIspList.graphql";
import {useContext} from "react";
import RoutingContext from "../routing/RoutingContext";
import {BoundReports} from "./report/BoundReports";
import {ChooseUnit} from "../unit/ChooseUnit";
// import {Stack, StackTitle, StackItem,} from "../../UiDebugSave/sample/Stack";

const graphql = require("babel-plugin-relay/macro");


interface MeIspListProps {
    isps: MeIspList$key;
}

//该组件也被report模块引用了；
/**获取更多...实际读取到的有效不重复记录数和排序字段有关，最好排序能够确保唯一性，比如附带上id做排序。不排序的重复概率大。默认排序 任务日期task.date,
 * */
export const MeIspList: React.FunctionComponent<MeIspListProps> = props => {
  const theme = useTheme();
  //const toast = useToast();
 // const {user,} = useSession();
  //const [, setLocation] = useLocation();
  //graphQl的查询usexxx钩子函数，无法主动从后端读取最新数据。
  //const { loading, userList:followings } = useFollowerIngs(false);
  let filtercomp={filter: { id:1 },
    offset:0,
    limit:5,
    orderBy: "id",
    asc: false
  };
  //const { loading, items:followings ,} = usePaginateQueryTask(filtercomp,check);
    const { data, refetch , loadNext,hasNext,isLoadingNext} = usePaginationFragment(
        graphql`
            fragment MeIspList on Query
            @refetchable(queryName: "findMeDetailsQuery") {
                findMeDetails(where: $iwhere,after:$after,first:$first,orderBy:$orderBy,asc:$asc)
                @connection(key: "Query_findMeDetails") {
                    edges {
                        node {id,type,feeOk,task{id,date}
                          isp{
                            id,no,entrust,conclusion,dev{id,oid,cod},bus{id task{id,date}}
                            ...BoundReports
                            }
                        }
                    }
                }
            }
        `,
        props.isps,
    );
    const { findMeDetails:list, }=data;
    const isps = list && list.edges && list.edges.map(edge => edge?.node);
  //搜索user的输入:
  const [query, setQuery] = React.useState("");

  //状态管理　relation＝当前显示的或者按钮点击事件产生,关注的user是谁。 null as any告警去除
  const [relation, setRelation] = React.useState(null as any);


  const [, setFilter] = React.useState({where:
        {cod:query },
     });

  const noUsers = !query && (isps?.length === 0);
  //界面轮播 setIndex切换显示界面；   //index不是组件外部那一个同名index；
  const [index, setIndex] = React.useState(0);
    const {history } = useContext(RoutingContext);

  function showRelation(item: any) {
    console.log("点击showRelation？item=", item);
    setRelation(item);
    setIndex(1);
  }

  React.useEffect(() => {
    //console.log("伪善setQueryResul02=" ,query,usersFind);
    let filtercomp={where:
        {cod:query },
      offset:0,
      first:5,
      orderBy: "useDt",
      asc: false
    };
    setFilter(filtercomp);
  }, [query]);
  //这两个useEffect的前后顺序不能颠倒，顺序非常重要，后面的依赖于前面的useEffect更新结果。
  //操作UI副作用；要进一步做修正性处理。
    const toast = useToast();
    const {barHeight } = useMMenuBarOcup(history.routeData?.isExact);
    const href = `/task/${relation?.task?.id}`;

    const {save, field}= window.history.state?.state??{};
    const [open, setOpen] = React.useState(save?.open || false);
    const filt= JSON.parse(sessionStorage['我的检验过滤']??'{}');
    const [servu, setServu] = React.useState(save?.servu || filt?.servu);
    const [cod, setCod] = React.useState<any>(save?.cod || filt?.cod);
    const [oid, setOid] = React.useState<any>(save?.oid || filt?.oid);
    const [ident, setIdent] = React.useState<any>(save?.ident || filt?.ident);
    const [no, setNo] = React.useState<any>(save?.no ||filt?.no);
    async function pseudoDiasave() {
        return { open,cod,oid,servu,ident,no };
    }
    const commitBlurRef =React.useRef<HTMLDivElement | null>(null);

  return (
      <>
    <Stack  navStyle={css({ position: 'sticky',  top: 0,})}
        style={{
           height: '100%',
        }}
      index={index}
      navHeight={40}
      onIndexChange={i => setIndex(i)}
      items={[
        {
          title: (
              <StackTitle
                  contentAfter={
                      <>
                          <VerticalMenu>
                              <DdMenuItem label="刷新吧" onClick={(e) => {
                                  refetch({}, { fetchPolicy: "network-only"});
                              }}/>
                          </VerticalMenu>
                          <MenuItem variant="ghost"  tight
                                    onClick={() => {
                                        setOpen(true)
                                    }}
                          >
                              <IconLayers />
                          </MenuItem>
                          <Dialog open={open} onOpenChange={setOpen}>
                              <DialogContent >
                                  <DialogHeading>
                                      我的检验过滤器
                                  </DialogHeading>
                                  <DialogDescription>
                                      <div css={{ padding: '0 1rem' }}>
                                          <form  method="get"  action="/"  css={{margin: 0, position: "relative" }}>
                                              <div>
                                                  <InputLine label={`设备代码:`}>
                                                      <CommitInput type="search" placeholder="精确匹配"
                                                                   value={cod || ''}   onSave={txt => setCod(txt||undefined) }
                                                      />
                                                  </InputLine>
                                                  <InputLine label={`监察识别码:`}>
                                                      <CommitInput type="search" placeholder="精确匹配"
                                                                   value={oid || ''}   onSave={txt => setOid(txt||undefined) }
                                                      />
                                                  </InputLine>
                                                  <InputLine label={`服务单位(进入挑选):`}>
                                                      <ChooseUnit id={servu?.id} name={servu?.name} field={'servu'}
                                                                  autoFocus={field==='servu'}  onCancel={() => { setServu(undefined) }}
                                                                  onDialog={async () => { return await pseudoDiasave() } }
                                                      />
                                                  </InputLine>
                                                  <InputLine label={`报告附加标识:`}>
                                                      <CommitInput  type="search"
                                                                    value={ident || ''}  onSave={txt => setIdent(txt||undefined) }
                                                      />
                                                  </InputLine>
                                                  <InputLine label={`报告编号:`}>
                                                      <CommitInput type="search"
                                                                   value={no || ''}  onSave={txt => setNo(txt||undefined) }
                                                      />
                                                  </InputLine>
                                                  <div
                                                      css={{
                                                          display: "flex",
                                                          marginTop: theme.spaces.lg,
                                                          justifyContent: "flex-end"
                                                      }}
                                                  >
                                                      <Input  type='reset'  value={'清空过滤'}
                                                              style={{margin: 'auto', width: undefined }}  css={{backgroundColor: 'wheat' }}
                                                              onClick={async () => {
                                                                  setCod(undefined); setOid(undefined); setIdent(undefined);
                                                                  setNo(undefined); setServu(undefined);
                                                              } }
                                                      />
                                                      <ButtonRefComp intent="primary"
                                                                     ref={commitBlurRef}  onPointerOver={(e :any) => { commitBlurRef!.current!.focus(); }}
                                                                     onPress={() => {
                                                                         setOpen(false);
                                                                         sessionStorage['我的检验过滤'] =JSON.stringify({cod,oid,servu,ident,no});
                                                                         history.push("/inspect", {time: Date()} );
                                                                         console.log(`刚设置检验列表过滤:`, sessionStorage['我的检验过滤']);
                                                                     } }
                                                      >
                                                          过滤器改完重查
                                                      </ButtonRefComp>
                                                  </div>
                                              </div>
                                          </form>
                                      </div>
                                  </DialogDescription>
                                  <DialogClose>关闭</DialogClose>
                              </DialogContent>
                          </Dialog>
                      </>
                  }
                  title={"我的活动的检验列表"}
              />
          ),
          content: (
            <StackItem  css={{
                  marginBottom: `${barHeight}`,
                 }}
               style={{ position: undefined, boxShadow:undefined ,height: "100%"}}
            >
              <div  css={{overflowY: "auto", height: "100%" }}>
                { noUsers && (
                  <Text
                    muted
                    css={{
                      fontSize: theme.fontSizes[0],
                      display: "block",
                      margin: theme.spaces.lg
                    }}
                  >
                    队列为空
                  </Text>
                )}

                <List>
                 {isps?.map((item,i) => {
                   //这样的<RouterLink <ListItem onPress={() =>showRelation ;可能会ListItem报错unmounted:仅当嵌入为报告/动态模板之内；
                   return (
                      <ListItem
                        key={item?.id}
                        interactive={ true }
                        onPress={async (e) => {
                          await showRelation({ ...item  } );
                          //这里一次点击两个都触发了：RouterLink + showRelation; 详情页面 +左边框内<Stack 状态切换。首先触发Stack下沉的，然后页内路由，已加载组件状态能保留。
                          e?.stopPropagation();
                          e?.preventDefault();
                         // setLocation(`/inspect/${item?.id}`);
                        } }
                        contentBefore={
                          <Avatar
                            size="sm"
                            src={item?.id}
                            name={item?.isp!.dev?.cod!}
                          />
                        }
                        primary={item?.isp!.dev?.cod||'无关联设备'}
                        secondary={ `结论: ${item?.isp!.conclusion||''}` }
                        contentAfter={
                            <IconChevronRight
                              color={theme.colors.text.muted}
                              aria-hidden
                            />
                        }
                      >
                        {`${item?.isp!.no!} 日期:${item?.task?.date}`}
                      </ListItem>
                    );
                  })}
                </List>
                 <div css={{textAlign: "center", paddingBottom:'3rem' }}>
                      <Button disabled={isLoadingNext}
                            onPress={async (e) => {
                             e?.stopPropagation();
                             await loadNext(20,{
                                 onComplete: (error) =>  {
                                 if(error){
                                 toast({
                                     title: "返回了",
                                     subtitle: ""+error,
                                     intent: "error"
                                 });
                                }
                               }
                            });
                         } }
                     >
                          {`${isps?.length}条 `}{hasNext? '获取更多...':'没有更多了'}
                      </Button>
                 </div>
              </div>
            </StackItem>
          )
        },

      {
          title: (
              <StackTitle
                  backTitle={"回退"}
                  contentAfter={
                      relation && (
                          <VerticalMenu>
                              <DdMenuItem label="加个检验主或分项报告" onClick={(e) => {
                                  history.push(`/inspect/${(relation as any).id}/addReport`);
                              }}/>
                              <DdMenuItem label="所属任务" onClick={(e) => {
                                  history.push(href);
                              }}/>
                          </VerticalMenu>
                      )
                  }
                  title={relation ? `检验${(relation as any).id}含报告` : ""}
              />
          ),
          content: (
              <StackItem  css={{ marginBottom: `${barHeight}`, }}
                     style={{  boxShadow:undefined }}
              >
                  { relation && (
                    <BoundReports key={relation?.isp.id!} id={relation?.isp.id!}
                        isp={relation.isp}
                    />
                  )}
              </StackItem>
          )
      }

      ]}
    />

      </>
  );

};





//报错Cannot read property 'map' of null标记出错代码行，竟可能会差错！实际错误点实在下方，报错指示却在上方的代码行，两处都有.map的代码。
//<Stack 组件，实际上是内部状态控制界面的呈现，实际上DOM数据内容并没有同步地变更，只是页面切换着看；适用数据库组织的；PK的，导航堆叠场景实际是源代码组织的。
//幸运的事！！<StackItem>底下内嵌的组件可以做到每一个都是独立自主的。这里<FollowingRecipes key={}/>对每一个按钮进入和后退的，虽然组件同一个，但内部状态数据可各自独立的。
//overflowY:"scroll"若遇到 css={{height: "100%", 和 minHeight: '300px' 不能同时添加的。overflowY:和"100%"一起使用，且要在内层DIV上用。组件中间层可能屏蔽掉。
//多层DIV的height: "100%", 需要在中间层次添加100%传递父辈限制大小，配合内部层的overflowY: "scroll",才能滚动。
//<Stack多层的下沉层叠＋<ListItem，配合<RouterLink，可以触发点击链接同时还能够下沉页面触发；左右两个页面都能刷新，可是小屏幕只能对照右半部分的核心界面。不触发下沉和要触发条目可同时用。
//点击一次触发多重：<RouterLink to={`/inspect/${item.id}`} >    /  <ListItem  onPress={() =>      /   <Button  onPress={e => { ；；
